package info.niwota.gae;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class ResourceServlet extends BaseServlet {
	private static final Logger log = Logger.getLogger(ResourceServlet.class
			.getName());
	public static final String[] CDN_MAP = new String[] {};
	private String baseUrl;
	
	//"/assets/opt/script/jquery.js","http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js", 
	
	public boolean handle(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		final String q = req.getQueryString();
		String uri = req.getRequestURI() + (q == null ? "" : "?" + q) ;

		log.info("uri: " + uri );

		for (int i = 0; i < CDN_MAP.length; i += 2) {
			if (CDN_MAP[i].equals(uri)) {
				resp.sendRedirect(CDN_MAP[i + 1]);
				return true;
			}
		}
		
		if (uri.startsWith("/res/drawable/")) {
			sendRedirect(req, resp, uri+".png");
			return true;
		}
		
		if (uri.startsWith("/icon/info.niwota.web")) {
			sendRedirect(req, resp, "/assets/image/icon.png");
			return true;
		}
		
		if (uri.equals("/favicon.ico")) {
			sendRedirect(req, resp, "/assets/image/favicon.png");
			return true;
		}
		
		if (uri.startsWith("/icon/")) {
			resp.sendRedirect("http://hotwebproxy.appspot.com" + uri);
			return true;
		}
		
		if (uri.equals("/wallpaper")) {
			sendRedirect(req, resp, "/assets/image/bg_blue_sky.jpg");
			return true;
		}
		
		if (uri.startsWith("/wallpaper/")) {
			resp.sendRedirect("http://sites.google.com/site/hotwebagent/hotweb" + uri);
			return true;
		}
		
		return false;
	}
	
	@Override
	public void init(ServletConfig config) throws ServletException {
		baseUrl = config.getInitParameter("baseUrl");
		baseUrl  = (baseUrl == null ? "" : baseUrl);
	}

	protected void sendRedirect(HttpServletRequest req, HttpServletResponse resp,
			String url) throws IOException {
		resp.sendRedirect(baseUrl + url);
	}
}
